package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.inter.vo.SkuSaleVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuService")
@Slf4j
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    //private SpuDescMapper spuDescMapper;
    private SpuDescService spuDescService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpuAttrValueService spuAttrValueService;

    @Autowired
    private SkuAttrValueService skuAttrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private GmallSmsClient gmallSmsClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 发送消息到mq
     * @param id
     * @param type
     */
    @Override
    public void sendMessage(Long id, String type) {
        //发送消息到mq
        try {
            this.rabbitTemplate.convertAndSend("item_exchange","item."+type,id);
        } catch (AmqpException e) {
            log.error("{}商品消息发送异常，商品id: {}",type,id,e);
        }

    }

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo querySpuByConditions(Long categoryId, PageParamVo pageParamVo) {

        QueryWrapper<SpuEntity> queryWrapper = new QueryWrapper<>();
        if (categoryId != 0){
            queryWrapper.eq("category_id",categoryId);
        }
        String key = pageParamVo.getKey();
        if (StringUtils.isNotBlank(key)){
            queryWrapper.and(t->t.like("id",key).or().like("name",key));
        }

        return new PageResultVo(this.page(pageParamVo.getPage(),queryWrapper));
    }

    @GlobalTransactional
    @Override
    public void bigSave(SpuVo spuVo) {
        //1.保存spu属性数据
        //1.1保存spu基本信息---------------pms_spu
        Long spuId = saveSpu(spuVo);
        //1.2 保存spu的描述信息-------------pms_spu_desc
        this.spuDescService.saveDesc(spuVo, spuId);

        //this.saveDesc(spuVo, spuId);
        /*在自己的service设置事务,获取代理对象
        SpuService proxy  = (SpuService) AopContext.currentProxy();
        proxy.saveDesc(spuVo, spuId);*/

        //int i = 1/0;

        //1.3 保存spu基本属性baseAttr的数据---------pms_spu_attr_value
        saveAttrValue(spuVo, spuId);

        //2.保存skuVo数据
        saveSku(spuVo, spuId);
        //发送消息到mq,为了数据同步
        sendMessage(spuVo.getId(), "insert");

        //int i = 1/0;


    }

    public void saveSku(SpuVo spuVo, Long spuId) {
        List<SkuVo> skus = spuVo.getSkus();
        if (CollectionUtils.isEmpty(skus)){
            return;
        }

        if (!CollectionUtils.isEmpty(skus)){
            skus.forEach(skuVo -> {
                //2.1 保存skuEntity数据-----------pms_sku
                SkuEntity skuEntity = new SkuEntity();
                BeanUtils.copyProperties(skuVo,skuEntity);

                skuEntity.setSpuId(spuId);
                skuEntity.setCategoryId(spuVo.getCategoryId());
                skuEntity.setBrandId(spuVo.getBrandId());
                //图片是集合取第一个作为默认的图片
                List<String> images = skuVo.getImages();
                if (!CollectionUtils.isEmpty(images)){
                    skuEntity.setDefaultImage(skuEntity.getDefaultImage()==null ? images.get(0) : skuEntity.getDefaultImage());
                }

                this.skuMapper.insert(skuEntity);
                Long skuId = skuEntity.getId();

                //2.2 保存图片信息----------------pms_sku_images
                if (!CollectionUtils.isEmpty(images)){

                    String defaultImg = images.get(0);
                    List<SkuImagesEntity> skuImages = images.stream().map(image -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();

                        skuImagesEntity.setUrl(image);
                        skuImagesEntity.setSort(0);
                        skuImagesEntity.setSkuId(skuId);
                        //设置第一个img的status为1 其他的status为0
                        skuImagesEntity.setDefaultStatus(StringUtils.equals(defaultImg, image) ? 1 : 0);

                        return skuImagesEntity;
                    }).collect(Collectors.toList());

                    this.skuImagesService.saveBatch(skuImages);
                }

                //2.3.保存sku销售属性数据----------pms_sku_attr_value
                List<SkuAttrValueEntity> skuAttrValueEntities = skuVo.getSaleAttrs();
                if (!CollectionUtils.isEmpty(skuAttrValueEntities)){
                    skuAttrValueEntities.forEach(skuAttrValueEntity -> {
                        skuAttrValueEntity.setSkuId(skuId);
                        skuAttrValueEntity.setSort(0);
                    });
                    this.skuAttrValueService.saveBatch(skuAttrValueEntities);
                }


                // 3. 保存营销相关信息，需要远程调用gmall-sms
                SkuSaleVo skuSaleVo = new SkuSaleVo();
                BeanUtils.copyProperties(skuVo,skuSaleVo);
                skuSaleVo.setSkuId(skuId);
                this.gmallSmsClient.saveSkuSaleInfo(skuSaleVo);

                // 3.1. 积分优惠------------------sms_sku_bounds
                // 3.2. 满减优惠------------------sms_sku_full_reduction
                // 3.3. 数量折扣------------------sms_sku_ladder
            });
        }
    }

    public void saveAttrValue(SpuVo spuVo, Long spuId) {
        List<SpuAttrValueVo> spuAttrValueVos = spuVo.getBaseAttrs();
        if (!CollectionUtils.isEmpty(spuAttrValueVos)){

            List<SpuAttrValueEntity> spuAttrValueEntities = spuAttrValueVos.stream().map(spuAttrValueVo -> {
                spuAttrValueVo.setSpuId(spuId);
                spuAttrValueVo.setSort(0);
                return spuAttrValueVo;
            }).collect(Collectors.toList());
            this.spuAttrValueService.saveBatch(spuAttrValueEntities);
        }
    }

    /*@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveDesc(SpuVo spuVo, Long spuId) {
        SpuDescEntity spuDescEntity = new SpuDescEntity();
        spuDescEntity.setSpuId(spuId);
        //获取spuImages并转换为String类型的
        List<String> spuImages = spuVo.getSpuImages();
        String desc = StringUtils.join(spuImages, ",");
        spuDescEntity.setDecript(desc);
        this.spuDescMapper.insert(spuDescEntity);
    }*/

    @Transactional
    public Long saveSpu(SpuVo spuVo) {
        spuVo.setPublishStatus(1);
        spuVo.setCreateTime(new Date());
        spuVo.setUpdateTime(spuVo.getCreateTime());
        this.save(spuVo);
        return spuVo.getId();
    }

}